package com.itfreer.gis.server.vector.generate;

import com.google.common.base.Preconditions;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;

/**
 * 定义Geometry处理器
 */
public abstract class Pipeline {

	protected static final Geometry EMPTY = new GeometryFactory().createPoint((Coordinate) null);

	/**
	 * 定义最后一个处理器
	 */
	static final Pipeline END = new Pipeline() {
		@Override
		public final Geometry execute(Geometry geom) {
			return geom;
		}

		@Override
		protected final Geometry _run(Geometry geom) {
			throw new UnsupportedOperationException();
		}
	};

	private Pipeline next = END;

	/**
	 * 设置下个处理器
	 * 
	 * @param step
	 */
	void setNext(Pipeline step) {
		Preconditions.checkNotNull(next);
		this.next = step;
	}

	/**
	 * 执行处理器
	 * 
	 * @param geom
	 * @return
	 * @throws Exception
	 */
	public Geometry execute(Geometry geom) throws Exception {
		Preconditions.checkNotNull(next, getClass().getName());
		Geometry g = _run(geom);
		if (g == null || g.isEmpty()) {
			return EMPTY;
		}
		return next.execute(g);
	}

	/**
	 * 当前处理器逻辑处理
	 * 
	 * @param geom
	 * @return
	 * @throws Exception
	 */
	protected abstract Geometry _run(Geometry geom) throws Exception;
}
